<template>
  <div class="vehicle-record-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="search-item">
              <span class="label">所属小区</span>
              <el-input
                  v-model="searchForm.communityName"
                  placeholder="请输入小区名称"
                  clearable
                  class="search-input"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="search-item">
              <span class="label">出入闸机</span>
              <el-input
                  v-model="searchForm.gateDevice"
                  placeholder="请输入闸机名称"
                  clearable
                  class="search-input"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="search-item">
              <span class="label">车主姓名</span>
              <el-input
                  v-model="searchForm.ownerName"
                  placeholder="请输入车主姓名"
                  clearable
                  class="search-input"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="search-actions">
              <el-button type="primary" @click="handleSearch" class="search-btn">
                查询
              </el-button>
              <el-button @click="handleReset" class="reset-btn">
                重置
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
          :data="tableData"
          stripe
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
        />
        <el-table-column
            prop="carNo"
            label="车牌号"
            width="80"
            align="center"
        />
        <el-table-column
            prop="vehicleType"
            label="车辆类型"
            width="80"
            align="center"
        />
        <el-table-column
            prop="ownerName"
            label="车主姓名"
            width="80"
            align="center"
        />
        <el-table-column
            prop="ownerPhone"
            label="手机号"
            width="80"
            align="center"
        />
        <el-table-column
            prop="gateDevice"
            label="出入闸机"
            width="80"
            align="center"
        />
        <el-table-column
            prop="paymentMethod"
            label="支付方式"
            width="80"
            align="center"
        />
        <el-table-column
            label="入场时间"
            width="110"
            align="center"
        >
          <template #default="scope">
            {{ formatDateTime(scope.row.entryTime) }}
          </template>
        </el-table-column>
        <el-table-column
            label="出场时间"
            width="110"
            align="center"
        >
          <template #default="scope">
            {{ formatDateTime(scope.row.exitTime) }}
          </template>
        </el-table-column>
        <el-table-column
            label="出入小区"
            width="80"
            align="center"
        >
          <template #default="scope">
            {{ scope.row.ownerCommunity?.name || '-' }}
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="60"
            align="center"
            fixed="right"
        >
          <template #default="scope">
            <el-button
                type="primary"
                link
                size="small"
                @click="handleView(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[3, 5, 10, 30]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {selectAllVehicleRecords} from '@/api/owner/record.js'
import { useRouter } from 'vue-router'


const router = useRouter()

// 搜索表单
const searchForm = reactive({
  communityName: '',
  gateDevice: '',
  ownerName: ''
})


// 表格数据
const tableData = ref([])
const loading = ref(false)


// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  initData()
}

// 重置处理
const handleReset = () => {
  Object.assign(searchForm, {
    communityName: '',
    gateDevice: '',
    ownerName: ''
  })
  pagination.currentPage = 1
  initData()
}

// 查看详情
const handleView = (row) => {
  console.log('=== 列表页面调试信息 ===')
  console.log('images 字段原始数据:', row.images)
  // 使用更安全的图片处理方式
  const getImageUrl = () => {
    if (!row.images) return null

    try {
      // 如果是数组
      if (Array.isArray(row.images)) {
        const firstImage = row.images[0]
        if (typeof firstImage === 'string') {
          return firstImage.startsWith('http') ? firstImage : null
        } else if (firstImage && firstImage.url) {
          return firstImage.url.startsWith('http') ? firstImage.url : null
        }
      }
      // 如果是字符串
      else if (typeof row.images === 'string') {
        // 尝试解析 JSON
        if (row.images.startsWith('[') || row.images.startsWith('{')) {
          try {
            const parsed = JSON.parse(row.images)
            if (Array.isArray(parsed) && parsed.length > 0) {
              const img = parsed[0]
              return typeof img === 'string' ? img : (img.url || null)
            }
          } catch (e) {
            // 解析失败，直接返回字符串
            return row.images.startsWith('http') ? row.images : null
          }
        }
        // 直接是 URL
        else if (row.images.startsWith('http')) {
          return row.images
        }
      }
    } catch (error) {
      console.error('处理图片时出错:', error)
    }

    return null
  }
  // 构建查询参数
  const queryParams = {
    carNo: row.carNo || '',
    vehicleType: row.vehicleType || '',
    ownerName: row.ownerName || '',
    ownerPhone: row.ownerPhone || '',
    community: row.ownerCommunity?.name || '',
    entryTime: row.entryTime || '',
    exitTime: row.exitTime || '',
    gateDevice: row.gateDevice || '',
    parkingDuration: formatParkingDuration(row.parkingDuration) || '',
    parkingFee: row.fee || '',
    paymentMethod: row.paymentMethod || '',
    imageUrl: getImageUrl(),
    // 添加时间戳确保路由唯一性
    timestamp: Date.now()
  }

  console.log('查询参数:', queryParams)
  console.log('图片URL:', queryParams.imageUrl)

  router.push({
    path: '/record/vehicleDetail',
    query: queryParams
  })
  console.log('查看记录:', row)
}
const formatParkingDuration = (minutes) => {
  if (!minutes || minutes === 0) return '-'

  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60

  if (hours > 0) {
    return `${hours}小时${mins > 0 ? `${mins}分钟` : ''}`
  } else {
    return `${mins}分钟`
  }
}
const getFirstImage = (images) => {
  if (!images || !Array.isArray(images) || images.length === 0) {
    return null
  }
  // 如果 images 是字符串数组，返回第一个
  if (typeof images[0] === 'string') {
    return images[0]
  }
  // 如果 images 是对象数组，假设有 url 属性
  if (images[0] && images[0].url) {
    return images[0].url
  }
  return null
}
// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  initData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  initData()
}


const initData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    // 添加搜索条件
    if (searchForm.communityName) {
      // 关键：使用 community.name 作为参数名
      params['ownerCommunity.name'] = searchForm.communityName
    }
    if (searchForm.gateDevice) params.gateDevice = searchForm.gateDevice
    if (searchForm.ownerName) params.ownerName = searchForm.ownerName


    console.log('查询参数:', params) // 调试用

    const response = await selectAllVehicleRecords(params)

    // 处理返回数据
    tableData.value = response.rows.map(item => ({
      ...item,
      // 如果需要字段转换可以在这里处理
      // 例如：communityName: item.community?.name
    }))

    pagination.total = response.total
    console.log('完整API响应:', response) // 查看完整响应结构
    ElMessage.success(response.msg)
    console.log('API返回原始数据:', response.rows)
  } catch (error) {
    console.error(error.response.data.msg)
    ElMessage.error(error.response.data.msg)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  initData()
})
</script>

<style scoped>
.vehicle-record-container {
  padding: 16px 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 50px);
}

.breadcrumb {
  margin-bottom: 16px;
  font-size: 14px;
  color: #666;
}

.breadcrumb .separator {
  margin: 0 8px;
  color: #ccc;
}

.breadcrumb .current {
  color: #1890ff;
  font-weight: 500;
}

.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
}

.search-form {
  padding: 16px 0;
}

.search-item {
  display: flex;
  align-items: center;
}

.search-item .label {
  width: 80px;
  text-align: right;
  margin-right: 12px;
  font-size: 14px;
  color: #333;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
}

.search-actions {
  display: flex;
  align-items: center;
  height: 32px;
  padding-left: 12px;
}

.search-btn,
.reset-btn {
  margin-right: 12px;
}

.table-card {
  border-radius: 4px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 16px 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}
</style>